package com.csnf.servlet;

import com.csnf.dao.ICourseDao;
import com.csnf.dao.impl.CourseDaoImpl;
import com.csnf.entity.Course;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

@WebServlet({"/getCourse","/deleteCourseById","/saveCourse"})
public class CourseServlet extends HttpServlet {
    ICourseDao iCourseDao = new CourseDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String servletPath = req.getServletPath();
        switch (servletPath){
            case "/getCourse":
                getCourse(req,resp);
                break;
            case "/deleteCourseById":
                deleteCourseById(req,resp);
                break;
        }
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        saveCourse(req,resp);
    }

    private void saveCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String count = req.getParameter("count");
        String startDate = req.getParameter("startDate");
        String endDate = req.getParameter("endDate");
        String teacher = req.getParameter("teacher");
        iCourseDao.save(new Course(null,name,Integer.parseInt(count), LocalDate.parse(startDate),LocalDate.parse(endDate),teacher));
        resp.sendRedirect("getCorse");

    }

    private void deleteCourseById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String id = req.getParameter("id");
        Integer integer = iCourseDao.deleteById(Integer.parseInt(id));
        if (integer > 0){
            req.setAttribute("msg","删除成功");
        }else {
            req.setAttribute("msg","删除失败");
        }
        req.getRequestDispatcher("/getCorse").forward(req,resp);
    }

    private void getCourse(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String name = req.getParameter("name");
        if (name != null){
            req.setAttribute("courses",iCourseDao.findByName(name));
        }else {
            req.setAttribute("courses",iCourseDao.findAll());
        }
        req.getRequestDispatcher("courseList.jsp").forward(req,resp);
    }
}
